package com.jvtd.nettyim.im.server.handler;

import com.jvtd.nettyim.im.protocol.request.LoginRequestPacket;
import com.jvtd.nettyim.im.protocol.response.LoginResponsePacket;
import com.jvtd.nettyim.im.session.Session;
import com.jvtd.nettyim.im.util.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.UUID;

/**
 * @author Created by neal.zhang
 * @date 2020/5/29 - 20:13
 */
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket msg) throws Exception {
        System.err.println(new Date() + "--->收到客户端请求...");
        LoginResponsePacket loginResponse = new LoginResponsePacket();
        loginResponse.setVersion(msg.getVersion());
        loginResponse.setUserName(msg.getUserName());
        if (valid(msg)) {
            loginResponse.setSuccess(true);
            String userId = randomUserId();
            loginResponse.setUserId(userId);
            SessionUtil.bindSession(new Session(userId,msg.getUserName()),ctx.channel());
        } else {
            loginResponse.setSuccess(false);
            loginResponse.setReason("账号密码错误");
            System.err.println("登录失败.");
        }
        ctx.channel().writeAndFlush(loginResponse);
    }

    /**
     * fake 校验
     *
     * @param msg
     * @return
     */
    private boolean valid(LoginRequestPacket msg) {
        return true;
    }

    private static String randomUserId() {
        return UUID.randomUUID().toString().split("-")[0];
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionUtil.unBindSession(ctx.channel());
    }
}
